package edu.tms.security;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import edu.tms.bean.Admin;
import edu.tms.bean.CharacterRole;
import edu.tms.bean.Role;
import edu.tms.bean.User;
import edu.tms.dao.AdminDaoImp;
import edu.tms.dao.CharacterRoleDaoImp;
import edu.tms.dao.RoleDaoImp;


/**
 * 身份认证
 * 对“Who are you ？”进行核实。通常涉及用户名和密码。
 * 这 个组件负责收集 principals 和 credentials，并将它们提交给应用系统。
 * 如果提交的 credentials 跟应用系统中提供的 credentials 吻合，就能够继续访问，
 * 否则需要重新提交 principals 和 credentials，或者直接终止访问。
 * 
 * @author Administrator
 *
 */
public class Authenticator {
	private Map<String, Integer> positions = new HashMap<>();
	

	public Authenticator(){
		
	}
	
	/**
	 * 身份认证
	 * @param user
	 * @return
	 */
	public Map<String, Integer> authenticate(User user){
		positions = setMap();
		int type = user.getUserType();
		switch(type){
		case 1:
			positions.put("学生", 1); 
			putPost(user.getUserId());
			break;
		case 2:
			positions.put("专业教师", 1); 
			break;
		case 3:
			positions.put("辅导员", 1);
			break;
		case 4:
			AdminDaoImp dao = new AdminDaoImp();
			try {
				Admin admin = dao.findByKey(user.getUserId());
				if(admin.getAdminType() == 1){
					positions.put("管理员", 1);
				}else if(admin.getAdminType() == 2) 
					positions.put("超级管理员", 1);
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		}
		return positions;
	}
	
	public void putPost(int userId){
		CharacterRoleDaoImp dao = new CharacterRoleDaoImp();
		try {
			List<CharacterRole> crs = dao.findAll(userId);
			for (CharacterRole cr : crs) {
				positions.put(cr.getRoleName(),1);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	public Map<String,Integer> setMap(){
		RoleDaoImp dao = new RoleDaoImp();
		Map<String,Integer> positions = new HashMap<String,Integer>();
		try {
			List<Role> roles = dao.findAll();
			for (Role role : roles) {
				if(role.getRoleState() == 1)positions.put(role.getRoleName(), 0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return positions;
	}
}
